<template>
  <div id="barChart1" style="width: 600px;height:400px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import axios from 'axios';

export default {
  name: 'BarChartComponent',
  data() {
    return {
      dateCategories: [], // 日期列表
      dailyTotals: {}, // 每个日期的总金额
    };
  },
  computed: {
    barChartData() {
      // 返回一个数组，代表每个日期的总金额
      return this.dateCategories.map(date => this.dailyTotals[date] || 0);
    },
  },
  mounted() {
    this.loadData().then(() => {
      this.initChart();
    }).catch((error) => {
      console.error('Error loading data:', error);
    });
  },
  methods: {
    async loadData() {
      try {
        const billInfoResponse = await axios.get('https://youxuan-zua-api.tulan.wang/admin/ysf-bill-info/findPage?page=1&size=20');

        this.dailyTotals = {};
        this.dateCategories = [];

        // 将数据按日期分组并计算总额
        billInfoResponse.data.data.forEach(item => {
          const date = this.formatDate(item.createTime);
          if (!this.dateCategories.includes(date)) {
            this.dateCategories.push(date);
          }
          this.dailyTotals[date] = (this.dailyTotals[date] || 0) + item.money;
        });

        // 确保日期按顺序排列
        this.dateCategories.sort();
      } catch (error) {
        throw new Error('Failed to load data.');
      }
    },
    formatDate(dateString) {
      // 格式化日期字符串，返回YYYY-MM-DD格式
      const date = new Date(dateString);
      return `${date.getFullYear()}-${this.padZero(date.getMonth() + 1)}-${this.padZero(date.getDate())}`;
    },
    padZero(num) {
      // 如果数字小于10，则前面加0
      return num < 10 ? `0${num}` : num;
    },
    initChart() {
      const myChart = echarts.init(document.getElementById('barChart'));
      const option = {
        title: {
          text: '每日交易额',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: this.dateCategories,
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '交易金额',
            type: 'bar',
            data: this.barChartData,
            barWidth: '60%',
            itemStyle: {
              color: '#5470C6'
            }
          }
        ]
      };

      myChart.setOption(option);
    },
  },
};
</script>